import React from 'react';
import './index.scss'
import axios from 'axios'
import { Link } from 'react-router-dom'
// import { hashHistory } from 'react-router'

class Site extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      city:[]
    }
  }
  // 获取城市信息
  getCity () {
    axios.get('http://localhost:3000/api/city/list').then(response => {
      var arr = response.data.data
      // console.log(arr)
      var hash = {} // 记录拼音首字母是否存在
      var i = 0 // 用来记录某个拼音首字母的下标
      var res = []
      arr.forEach(item => {
        let py = item.pinyin.substring(0, 1).toUpperCase()
        // console.log(py)
        if (hash[py]) {
          res[hash[py] - 1].list.push(item)
        } else {
          hash[py] = ++i
          res.push({
            py: py,
            list: [item]
          })
        }
      })
      this.setState({
        city:res
      })
      this.sortCity()
      console.log(this.state.city)
    })
  }

  // 顺序排序
  sortCity () {
    for (var i = 0; i < this.state.city.length; i++) {
      for (var j = i + 1; j < this.state.city.length; j++) {
        if (this.state.city[i].py > this.state.city[j].py) {
          [this.state.city[i], this.state.city[j]] = [this.state.city[j], this.state.city[i]]
        }
      }
    }
  }

  // 获取点击的城市
  getSite(siteName) {
    console.log(siteName);
    // 把获取的城市存入到localStorage中
    localStorage.setItem("siteName",siteName);
  }

  componentWillMount() {
    this.getCity()
  }

  render() {
    // 获取城市信息
    var list = this.state.city.map((item,i) => (
      <div key={ i } className="site-list">
        <span className="site-eng">{ item.py }</span>
        <ul>
          { 
            item.list.map((item,i) => (
              <li key={i} onClick={ this.getSite.bind(this,item.name) }>
                <Link to="/films">{ item.name }</Link>
              </li>
            ))
          }
        </ul>
      </div>
    ))
    return (
      <div className="site">
        <div className="site-header">
          <i className="iconfont icon-arrow-right-copy-copy-copy"></i>
          <span>城市选择</span>
        </div>
        <div className="site-search">
          <div className="site-inp">
            <i className="iconfont icon-search"></i>
            <input type="search" placeholder="请输入城市名或者拼音" />
          </div>
        </div>
        <div className="site-slit">
          { list }
        </div>
      </div>
    )
  }
}

export default Site;
